package com.lzx.adx.report.support.strategy.v2.media;

import cn.hutool.core.util.URLUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.lzs.adx.commmon.utils.Result;
import com.lzx.adx.report.annnotions.MediaType;
import com.lzx.adx.report.constant.MediaChannelConstant;
import com.lzx.adx.report.dto.AccountDTO;
import com.lzx.adx.report.dto.ReportDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * 快手
 */
@Slf4j
@Component
@MediaType(MediaChannelConstant.KS)
public class KsCallBackStrategy extends AbstractCallback{
    @Override
    public ResponseEntity callback(ReportDTO reportDTO, AccountDTO accountDTO, String callType, String ts) {
        boolean base = base(reportDTO, accountDTO, callType, ts);
        if(!base){
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }

        String sspExtend = accountDTO.getSspExtend();
        JSONObject jsonObject = JSONObject.parseObject(sspExtend);
        String eventType = jsonObject.getString(callType);


        //2.回调渠道，调用快手回传接口
        Map<String, Object> reqParams = new HashMap<>();
        reqParams.put("event_type", eventType);
        reqParams.put("event_time", ts);
        //组装参数和url
        String finalReqUrl = reportDTO.getCallback() + "&" + URLUtil.buildQuery(reqParams, StandardCharsets.UTF_8);

        log.info("账号id{},请求id{} 给快手上报回传完整的地址：{}", reportDTO.getDspId(), reportDTO.getBizRequestId(), finalReqUrl);
        String result = HttpUtil.createGet(finalReqUrl).execute().body();
        log.info("账号id{},请求id{} 给快手报回传结果为 {}", reportDTO.getDspId(), reportDTO.getBizRequestId(), result);

        return ResponseEntity.ok(new Result());
    }
}
